<template>
<!--  图片裁剪组件 -->
  <div>
    <div
      style="border:1px solid #409EFF;width:79px;text-align:center;color:#409EFF;border-radius:3px;padding:4px 0px;margin-bottom:20px"
    >
      <label class="btn btn-orange" for="uploads">选择图片</label>
    </div>
    <div class="info-item">
      <div class="line" style="margin-bottom:20px;">
        <div class="cropper-content" style="height:300px;">
          <div class="cropper">
            <vueCropper
              ref="cropper"
              :img="option.img"
              :outputSize="option.size"
              :outputType="option.outputType"
              :info="true"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight"
              :fixedBox="option.fixedBox"
              @realTime="realTime"
              @imgLoad="imgLoad"
            ></vueCropper>
          </div>
          <div
            style="display:flex;flex-direction:column;justify-content:space-around;margin-left:20px"
          >
            <div class="oper">
              <input
                type="button"
                value="+"
                title="放大"
                @click="changeScale(1)"
                style="width:28px;height:28px;background-color:#E5E5E5;font-size:20px;border-radius:50%"
              />
            </div>
            <div class="oper">
              <input
                type="button"
                value="-"
                title="缩小"
                @click="changeScale(-1)"
                style="width:28px;height:28px;background-color:#E5E5E5;font-size:20px;border-radius:50%"
              />
            </div>
            <div class="oper">
              <input
                type="button"
                value="↺"
                title="左旋转"
                @click="rotateLeft"
                style="width:28px;height:28px;background-color:#E5E5E5;font-size:20px;border-radius:50%"
              />
            </div>
            <div class="oper">
              <input
                type="button"
                value="↻"
                title="右旋转"
                @click="rotateRight"
                style="width:28px;height:28px;background-color:#E5E5E5;font-size:20px;border-radius:50%"
              />
            </div>
            <div class="oper">
              <input
                type="button"
                value="↓"
                title="下载"
                @click="down('blob')"
                style="width:28px;height:28px;background-color:#E5E5E5;font-size:20px;border-radius:50%"
              />
            </div>
            <input
              type="file"
              id="uploads"
              :value="imgFile"
              style="position:absolute; clip:rect(0 0 0 0);"
              accept="image/png, image/jpeg, image/gif, image/jpg"
              @change="uploadImg($event, 1)"
            />
          </div>
          <div style="border:1px solid gray;width:0px;height:260px;margin-left:50px"></div>
          <div style="margin-left:50px;display:flex;flex-direction:column;">
            <div class="show-preview" v-if="picIndex==0">
              <div :style="previews.div" class="preview">
                <img :src="previews.url" :style="previews.img" />
              </div>
            </div>
            <div class="show-preview" v-if="picIndex!=0">
              <div :style="previews.div" class="preview1">
                <img :src="previews.url" :style="previews.img" />
              </div>
            </div>
            <div style="text-align:center;margin-left:40px;font-size:18px">效果预览</div>
          </div>
        </div>
      </div>
      <div style="text-align:center;">
        <el-button
          type="primary"
          @click="finish('blob')"
          style="text-align:center;margin-bottom:20px;"
        >确认上传</el-button>
      </div>
    </div>
  </div>
</template>
 
<script>
import { VueCropper } from "vue-cropper";
import { compress } from "./image.js";

export default {
  data() {
    return {
      headImg: "",
      //剪切图片上传
      crap: false,
      previews: {},
      option: {
        img: "",
        outputSize: 0.1, //剪切后的图片质量（0.1-1）
        full: true, //输出原图比例截图 props名full
        outputType: "jpeg",
        canMove: true,
        original: false,
        canMoveBox: true,
        autoCrop: true,
        autoCropWidth: 150,
        autoCropHeight: 150,
        fixedBox: false,
      },
      fileName: "", //本机文件地址
      downImg: "#",
      imgFile: "",
      nowIndex: -1,
      // uploadImgRelaPath:'', //上传后的图片的地址（不带服务器域名）
    };
  },
  components: {
    VueCropper,
  },
  props: {
    picIndex: {
      type: Number,
      default: -1,
    },
    subPicUrl: {
      type: String,
      default: "",
    },
  },
  watch: {
    subPicUrl: {
      handler(val) {},
    },
  },
  methods: {
    //图片跨域问题
    imgTrick(src) {
      let img = document.querySelector(".cropper-box-canvas img");
      let box_canvas = document.querySelector(".cropper-box-canvas");
      if (!img) {
        let img = new Image();
        img.src = src;
        img.crossOrigin = "anonymous";
        box_canvas.append(img);
      }
    },
    //放大/缩小
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    //坐旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    //右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    //清除截图
    clearCrop() {
      this.$refs.cropper.clearCrop();
    },
    //重新加载图片
    refreshCrop() {
      // clear
      this.$refs.cropper.refresh();
    },
    //停止截图
    stopCrop() {
      this.$refs.cropper.stopCrop();
    },
    //上传图片（点击上传按钮）
    finish(type) {
      let _this = this;
      let formData = new FormData();
      // 输出
      if (type === "blob") {
        this.$refs.cropper.getCropBlob((data) => {
          let img = window.URL.createObjectURL(data);
          this.model = true;
          this.modelSrc = img;
          var file = new File([data], this.fileName, {
            type: type,
            lastModified: Date.now(),
          });
          //压缩图片
          // formData.append("file", data, this.fileName);
          compress(file, function (val) {
            if (!val.name) {
              val.name = file.name;
            }
            var file2 = new File([val], val.name, {
              type: val.type,
              lastModified: Date.now(),
            });
            formData.append("source", file2);

            //blob转file
            // this.$http.post(Api.uploadSysHeadImg.url, formData, {contentType: false, processData: false, headers:{'Content-Type': 'application/x-www-form-urlencoded'}})
            _this
              .$axios({
                method: "post",
                url: "/api/uploads/uploads",
                data: formData,
              })
              .then((res) => {
                if (res.data.size.unit == "MB") {
                  _this.$message.error("图片大小已超出1MB,上传失败");
                } else {
                  if (res.data.url) {
                    // $('#btn1').val('');
                    _this.imgFile = "";
                    _this.headImg = res.data.url; //完整路径
                    _this.$emit("uploadIMG", res.data);
                    _this.$refs.cropper.refresh();
                    _this.uploadVisible = false;
                    // _this.uploadImgRelaPath = res.relaPathList[0];  //非完整路径
                    _this.$message({
                      //element-ui的消息Message消息提示组件
                      type: "success",
                      message: "上传成功",
                    });
                    _this.option.img = "";
                  } else {
                    _this.uploadVisible = false;
                  }
                }
              });
          });
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          this.model = true;
          this.modelSrc = data;
        });
      }
    },
    // 实时预览函数
    realTime(data) {
      // console.log(data);
      this.previews = data;
    },
    //下载图片
    down(type) {
      var aLink = document.createElement("a");
      aLink.download = "author-img";
      if (type === "blob") {
        this.$refs.cropper.getCropBlob((data) => {
          this.downImg = window.URL.createObjectURL(data);
          aLink.href = window.URL.createObjectURL(data);
          aLink.click();
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          this.downImg = data;
          aLink.href = data;
          aLink.click();
        });
      }
    },
    //选择本地图片
    uploadImg(e, num) {
      var _this = this;
      //上传图片
      var file = e.target.files[0];
      _this.fileName = file.name;
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        if (num === 1) {
          _this.option.img = data;
        } else if (num === 2) {
          _this.example2.img = data;
        }
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(file);
    },
    imgLoad(msg) {},
  },
};
</script>
 
<style scoped lang="less">
.info {
  width: 720px;
  margin: 0 auto;
  .oper-dv {
    height: 20px;
    text-align: right;
    margin-right: 100px;
    a {
      font-weight: 500;
      &:last-child {
        margin-left: 30px;
      }
    }
  }
  .oper {
    width: 38px;
    height: 38px;
  }
  .info-item {
    margin-top: 15px;
    label {
      display: inline-block;
      width: 100px;
      text-align: right;
    }
    .sel-img-dv {
      position: relative;
      .sel-file {
        position: absolute;
        width: 90px;
        height: 30px;
        opacity: 0;
        cursor: pointer;
        z-index: 2;
      }
      .sel-btn {
        position: absolute;
        cursor: pointer;
        z-index: 1;
      }
    }
  }
}
.cropper-content {
  // display: flex;
  display: -webkit-flex;
  // justify-content: flex-end;
  // -webkit-justify-content: flex-end;
  .cropper {
    width: 260px;
    height: 260px;
  }
  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    .preview {
      overflow: hidden;
      border-radius: 50%;
      border: 1px solid #cccccc;
      background: #cccccc;
      // margin-left: 40px;
    }
    .preview1 {
      overflow: hidden;
      // border-radius: 50%;
      border: 1px solid #cccccc;
      background: #cccccc;
      // margin-left: 40px;
    }
  }
}
</style>